<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4">
      <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <!-- 头部区域 -->
        <div class="p-6 border-b border-gray-100">
          <h2 class="text-2xl font-semibold text-gray-800">错误代码转换工具</h2>
          <p class="mt-2 text-gray-600">将错误代码文件转换为 JSON 格式和 SQL 语句</p>
        </div>

        <!-- 主要内容区域 -->
        <div class="p-6">
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 输入区域 -->
            <div class="space-y-4">
              <div class="flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-700">错误代码输入</h3>
                <div class="space-x-2">
                  <button 
                    @click="clearInput" 
                    class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-red-600 bg-red-50 rounded-md hover:bg-red-100 transition-colors duration-200"
                  >
                    <i class="ri-delete-bin-line mr-1"></i> 清空
                  </button>
                  <input
                    type="file"
                    @change="handleFileUpload"
                    accept=".txt"
                    class="hidden"
                    ref="fileInput"
                  >
                  <button 
                    @click="$refs.fileInput.click()"
                    class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-blue-600 bg-blue-50 rounded-md hover:bg-blue-100 transition-colors duration-200"
                  >
                    <i class="ri-upload-line mr-1"></i> 上传文件
                  </button>
                </div>
              </div>
              <textarea
                v-model="inputText"
                placeholder="请输入错误代码文本或上传文件..."
                class="w-full h-[400px] p-4 text-sm font-mono bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              ></textarea>
            </div>

            <!-- 输出区域 -->
            <div class="space-y-4">
              <div class="flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-700">转换结果</h3>
                <div class="space-x-2">
                  <button 
                    @click="copyToClipboard('json')" 
                    class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-green-600 bg-green-50 rounded-md hover:bg-green-100 transition-colors duration-200"
                  >
                    <i class="ri-file-copy-line mr-1"></i> 复制JSON
                  </button>
                  <button 
                    @click="copyToClipboard('sql')" 
                    class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-purple-600 bg-purple-50 rounded-md hover:bg-purple-100 transition-colors duration-200"
                  >
                    <i class="ri-file-copy-line mr-1"></i> 复制SQL
                  </button>
                  <button 
                    @click="convert" 
                    class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 transition-colors duration-200"
                  >
                    <i class="ri-arrow-right-line mr-1"></i> 转换
                  </button>
                </div>
              </div>
              <div class="space-y-4">
                <div class="bg-gray-50 rounded-lg p-4">
                  <h4 class="text-sm font-medium text-gray-700 mb-2">JSON 格式</h4>
                  <pre class="text-sm font-mono overflow-auto max-h-[200px] whitespace-pre-wrap">{{ jsonOutput }}</pre>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                  <h4 class="text-sm font-medium text-gray-700 mb-2">SQL 语句</h4>
                  <pre class="text-sm font-mono overflow-auto max-h-[200px] whitespace-pre-wrap">{{ sqlOutput }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const inputText = ref('')
const jsonOutput = ref('')
const sqlOutput = ref('')
const fileInput = ref(null)

const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      inputText.value = e.target.result
    }
    reader.readAsText(file)
  }
}

const convert = () => {
  try {
    // 将输入文本按行分割
    const lines = inputText.value.split('\n').filter(line => line.trim())
    const errorMap = {}
    let currentCode = null
    let currentMessage = []

    // 解析错误代码和消息
    for (const line of lines) {
      const codeMatch = line.match(/^-\d+/)
      if (codeMatch) {
        if (currentCode && currentMessage.length > 0) {
          errorMap[currentCode] = currentMessage.join('\n').trim()
        }
        currentCode = codeMatch[0]
        currentMessage = []
      } else if (currentCode) {
        currentMessage.push(line.trim())
      }
    }

    // 处理最后一个错误代码
    if (currentCode && currentMessage.length > 0) {
      errorMap[currentCode] = currentMessage.join('\n').trim()
    }

    // 生成 JSON 输出
    jsonOutput.value = JSON.stringify(errorMap, null, 2)

    // 生成 SQL 输出
    const sqlStatements = []
    sqlStatements.push('CREATE TABLE IF NOT EXISTS genero_error_zhcn (')
    sqlStatements.push('  id INT AUTO_INCREMENT PRIMARY KEY,')
    sqlStatements.push('  error_code VARCHAR(10) NOT NULL,')
    sqlStatements.push('  error_message TEXT NOT NULL')
    sqlStatements.push(');')
    sqlStatements.push('')

    Object.entries(errorMap).forEach(([code, message]) => {
      const escapedMessage = message.replace(/'/g, "''")
      sqlStatements.push(
        `INSERT INTO genero_error_zhcn (error_code, error_message) VALUES ('${code}', '${escapedMessage}');`
      )
    })

    sqlOutput.value = sqlStatements.join('\n')

    ElMessage.success('转换成功')
  } catch (error) {
    ElMessage.error('转换失败：' + error.message)
  }
}

const clearInput = () => {
  inputText.value = ''
  jsonOutput.value = ''
  sqlOutput.value = ''
  ElMessage.info('已清空')
}

const copyToClipboard = async (type) => {
  try {
    const text = type === 'json' ? jsonOutput.value : sqlOutput.value
    await navigator.clipboard.writeText(text)
    ElMessage.success(`已复制${type === 'json' ? 'JSON' : 'SQL'}到剪贴板`)
  } catch (error) {
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
/* 自定义滚动条样式 */
pre, textarea {
  scrollbar-width: thin;
  scrollbar-color: #E5E7EB transparent;
}

pre::-webkit-scrollbar,
textarea::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

pre::-webkit-scrollbar-track,
textarea::-webkit-scrollbar-track {
  @apply bg-transparent;
}

pre::-webkit-scrollbar-thumb,
textarea::-webkit-scrollbar-thumb {
  @apply bg-gray-200 rounded-full;
}

pre::-webkit-scrollbar-thumb:hover,
textarea::-webkit-scrollbar-thumb:hover {
  @apply bg-gray-300;
}
</style> 